﻿' ******************************************************************************
' ** 
' **  Yahoo! Managed
' **  Written by Marius Häusler 2011
' **  It would be pleasant, if you contact me when you are using this code.
' **  Contact: YahooFinanceManaged@gmail.com
' **  Project Home: http://code.google.com/p/yahoo-finance-managed/
' **  
' ******************************************************************************
' **  
' **  Copyright 2011 Marius Häusler
' **  
' **  Licensed under the Apache License, Version 2.0 (the "License");
' **  you may not use this file except in compliance with the License.
' **  You may obtain a copy of the License at
' **  
' **    http://www.apache.org/licenses/LICENSE-2.0
' **  
' **  Unless required by applicable law or agreed to in writing, software
' **  distributed under the License is distributed on an "AS IS" BASIS,
' **  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
' **  See the License for the specific language governing permissions and
' **  limitations under the License.
' ** 
' ******************************************************************************


Namespace YahooManaged.Weather.API


    Public Class LocationIDSearchDownload
        Inherits Base.Download

        Public Event AsyncDownloadCompleted(ByVal sender As Base.Download, ByVal ea As LocationIDSearchDownloadCompletedEventArgs)


        Public Function Download(ByVal keyword As String, ByVal opt As ResultCountOptions) As LocationIDSearchResponse
            Return Me.Download(New String() {keyword}, opt)
        End Function
        Public Function Download(ByVal keywords() As String, ByVal opt As ResultCountOptions) As LocationIDSearchResponse
            Return Me.ToResponse(MyBase.DownloadStream(Me.DownloadUrl(keywords, opt)))
        End Function

        Public Overloads Sub DownloadAsync(ByVal keyword As String, ByVal opt As ResultCountOptions, Optional ByVal userArgs As Object = Nothing)
            Me.DownloadAsync(New String() {keyword}, opt)
        End Sub
        Public Overloads Sub DownloadAsync(ByVal keywords() As String, ByVal opt As ResultCountOptions, Optional ByVal userArgs As Object = Nothing)
            If keywords Is Nothing Then : Throw New ArgumentNullException("keywords", "The passed list is null.")
            Else
                Dim args As New AsyncDownloadArgs(userArgs) With {.Keywords = keywords}
                MyBase.DownloadStreamAsync(Me.DownloadUrl(keywords, opt), args)
            End If
        End Sub

        Private Sub DownloadAsync_Completed(ByVal sender As Base.Download, ByVal e As Base.StreamDownloadCompletedEventArgs) Handles MyBase.AsyncStreamDownloadCompleted
            Dim dlArgs As AsyncDownloadArgs = DirectCast(e.UserArgs, AsyncDownloadArgs)
            Dim args As New LocationIDSearchDownloadCompletedEventArgs(dlArgs.UserArgs, Me.ToResponse(e.Response), dlArgs.Keywords)
            RaiseEvent AsyncDownloadCompleted(Me, args)
        End Sub


        Private Function ToResponse(ByVal resp As Base.StreamResponse) As LocationIDSearchResponse
            Dim lst As New List(Of LocationID)
            Dim results() As XmlNode = mHelper.GetResultsFromXml(resp.Result, "loc")
            For Each locNode As XmlNode In results
                Dim loc As New LocationID
                loc.Name = locNode.InnerText
                Dim att As XmlAttribute = locNode.Attributes("id")
                If att IsNot Nothing Then loc.ID = att.InnerText
                lst.Add(loc)
            Next
            Return New LocationIDSearchResponse(resp.Connection, lst.ToArray)
        End Function

        Private Function DownloadUrl(ByVal keywords As IEnumerable(Of String), ByVal opt As ResultCountOptions) As String
            Dim whereClause As New Text.StringBuilder
            whereClause.Append("query in (")
            Dim lst As New List(Of String)
            If keywords IsNot Nothing Then lst.AddRange(keywords)
            If lst.Count > 0 Then
                For i As Integer = 0 To lst.Count - 1
                    whereClause.Append(""""c)
                    whereClause.Append(lst(i).ToString)
                    whereClause.Append(""""c)
                    If i <> lst.Count - 1 Then whereClause.Append(","c)
                Next
            End If
            whereClause.Append(")"c)

            Return mHelper.YqlUrl("*"c, "weather.search", whereClause.ToString, opt, False)
        End Function



        Private Class AsyncDownloadArgs
            Inherits Base.DownloadEventArgs
            Public Keywords As IEnumerable(Of String)
            Public Sub New(ByVal userArgs As Object)
                MyBase.New(userArgs)
            End Sub
        End Class

    End Class




    Public Class LocationIDSearchResponse
        Inherits Base.Response
        Public Overloads ReadOnly Property Result() As LocationID()
            Get
                Return TryCast(MyBase.Result, LocationID())
            End Get
        End Property
        Friend Sub New(ByVal info As Base.ConnectionInfo, ByVal result As LocationID())
            MyBase.New(info, result)
        End Sub
    End Class



    Public Class LocationIDSearchDownloadCompletedEventArgs
        Inherits Base.DownloadCompletedEventArgs
        Private mKeywords As IEnumerable(Of String)
        Public ReadOnly Property Keywords() As IEnumerable(Of String)
            Get
                Return mKeywords
            End Get
        End Property
        Public Overloads ReadOnly Property Response() As LocationIDSearchResponse
            Get
                Return DirectCast(MyBase.Response, LocationIDSearchResponse)
            End Get
        End Property
        Friend Sub New(ByVal userArgs As Object, ByVal resp As LocationIDSearchResponse, ByVal keywords As IEnumerable(Of String))
            MyBase.New(userArgs, resp)
            mKeywords = keywords
        End Sub
    End Class


End Namespace